const db = uniCloud.database();
const dbCmd = db.command;
const { groupApplyChangeSendMessage } = require('../push/index.js');
const { chapterNameSplitStr } = require('../../config/index.js');
module.exports = async function(options = {}) {
	const { characterId, groupCode, applyStatus, applyCharacterId } = options;
	const token = this.getUniIdToken();
	const { appId } = this.getClientInfo();
	if (!characterId || !token) {
		throw new Error('非法访问');
	}
	const [groupList, applyList] = await Promise.all([
		db.collection('a-dz-group-list').where({ groupCode }).get({ getOne: true }),
		db.collection('a-dz-group-apply-list').where({ characterId: applyCharacterId, groupCode }).get({ getOne: true })
	])
	if (groupList.data.length) {
		const group = groupList.data[0];
		const apply = applyList.data.length && applyList.data[0] ? applyList.data[0] : {};
		//群主或申请者可以修改
		if (group.characterId == characterId || apply.characterId == characterId) {
			const group_chapters_custom = group.chapters_custom.map(item => `${groupCode}${chapterNameSplitStr}${item}`);
			await Promise.all([
				db.collection('a-dz-group-apply-list').where({ groupCode }).update({
					applyStatus
				}),
				db.collection('uni-id-users').doc(apply.uid).update({
					chapters: dbCmd.addToSet({
						$each: group.chapters
					}),
					chapters_custom: dbCmd.addToSet({
						$each: group_chapters_custom
					})
				}),
				groupApplyChangeSendMessage({
					uid: apply.uid,
					groupItem: group
				})
			])
		} else {
			throw new Error('非法操作');
		}
		return {
			code: 0,
			msg: '修改成功'
		}
	} else {
		throw new Error('非法操作');
	}
}